package com.gmt;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author John.zhang
 * @version Id: ConsumerController, v 1.0 2020/11/17 14:35 ZhiYong Exp $
 */
@RestController
public class ConsumerController {

    @Resource
    private RestTemplate restTemplate;

    /**
     * LoadBalanced
     * 具备负载均衡的能力
     *
     * @return
     */
    @Bean
    //@LoadBalanced 启用loadBalancerClient不需要设置LoadBalanced，避免URL的转换，因为已经是IP地址了
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @Resource
    private LoadBalancerClient loadBalancerClient;



    @GetMapping("/consumer")
    public String consumer() {
        return restTemplate.getForObject("http://springcloud-provider-service/hello", String.class);
    }

    @GetMapping("/consumer2")
    public String consumer2() {
        ServiceInstance choose = loadBalancerClient.choose("springcloud-provider-service");
        String url = String.format("http://%s:%s", choose.getHost(), choose.getPort() + "/hello");
        return restTemplate.getForObject(url, String.class);
    }

}
